package com.example.ems.servlet;

import com.example.ems.bean.Department;
import com.example.ems.bean.Employee;
import com.example.ems.dao.DepartmentDAO;
import com.example.ems.dao.EmployeeDAO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet {
    private EmployeeDAO employeeDAO;
    private DepartmentDAO departmentDAO; // For dropdown

    public void init() {
        employeeDAO = new EmployeeDAO();
        departmentDAO = new DepartmentDAO();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        String idStr = request.getParameter("id");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String position = request.getParameter("position");
        String deptIdStr = request.getParameter("deptId");
        String hireDateStr = request.getParameter("hireDate");

        Employee employee = new Employee();
        if (idStr != null && !idStr.isEmpty()) {
            employee.setId(Integer.parseInt(idStr));
        }
        employee.setName(name);
        employee.setEmail(email);
        employee.setPosition(position);
        if (deptIdStr != null && !deptIdStr.isEmpty() && !deptIdStr.equals("0")) {
            employee.setDeptId(Integer.parseInt(deptIdStr));
        } else {
            employee.setDeptId(0); // Or handle as an error if department is mandatory
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (hireDateStr != null && !hireDateStr.isEmpty()) {
                employee.setHireDate(sdf.parse(hireDateStr));
            }
        } catch (ParseException e) {
            e.printStackTrace(); // Handle error
        }

        if ("add".equals(action)) {
            employeeDAO.addEmployee(employee);
        } else if ("update".equals(action)) {
            employeeDAO.updateEmployee(employee);
        }
        response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        String searchName = request.getParameter("searchName"); // 获取查询参数
        request.setAttribute("searchNameVal", searchName); // 回传

        if (action == null) action = "list";

        List<Department> listDepartment = departmentDAO.getAllDepartments();
        request.setAttribute("listDepartment", listDepartment);

        switch (action) {
            case "new":
                // ... (原有 new 逻辑) ...
                request.getRequestDispatcher("/employee_form.jsp").forward(request, response);
                break;
            case "edit":
                // ... (原有 edit 逻辑) ...
                int id = Integer.parseInt(request.getParameter("id"));
                Employee existingEmp = employeeDAO.getEmployeeById(id);
                request.setAttribute("employee", existingEmp);
                request.getRequestDispatcher("/employee_form.jsp").forward(request, response);
                break;
            case "delete":
                // ... (原有 delete 逻辑) ...
                int deleteId = Integer.parseInt(request.getParameter("id"));
                employeeDAO.deleteEmployee(deleteId);
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list" + (searchName != null ? "&searchName=" + java.net.URLEncoder.encode(searchName, "UTF-8") : ""));
                break;
            case "list":
            default:
                List<Employee> listEmployee;
                if (searchName != null && !searchName.trim().isEmpty()) {
                    listEmployee = employeeDAO.getEmployeesByName(searchName.trim());
                } else {
                    listEmployee = employeeDAO.getAllEmployees();
                }
                request.setAttribute("listEmployee", listEmployee);
                request.getRequestDispatcher("/employee_list.jsp").forward(request, response);
                break;
        }
    }
}
